//
//  YAPicBrowserController.swift
//  KeepCliming
//
//  Created by 鱼龙之梦 on 15/9/14.
//  Copyright © 2015年 panyanzhi. All rights reserved.
//

import UIKit
import SVProgressHUD
private let YAPicBrowserCellID = "YAPicBrowserCellID"
class YAPicBrowserController: UIViewController {
    //MARK:--- 控制器属性
    var urls:[NSURL]
    var selectedIndexPath:NSIndexPath
    ///  当前用户在图片浏览器选中图像的索引
    var currentImageIndex:NSIndexPath{
        return collectionView.indexPathsForVisibleItems().last!
    }
    //当前选中图像的视图
    var currentImageView:UIImageView{
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex) as! YAPicBrowserCell
        return cell.imageView
    }
    //MARK:--- 保存图像
    @objc private func savaImage(){
        //获取图片
        //let cell = collectionView.cellForItemAtIndexPath(path) as! YAPicBrowserCell
        //cell不一定下载好了图片
        guard let image = currentImageView.image else{
            SVProgressHUD.showInfoWithStatus("没有图像")
            return
        }
        //保存图像
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)//要实现隐含调用方法
    }
    //MARK:--- 保存图像完成后的方法
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject){
        // printLog(error)
        let message = (error == nil) ? "保存成功":"保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
    //MARK:--- 用这俩个属性构造实例
    init(urls:[NSURL],indexPath:NSIndexPath){
        self.urls = urls
        selectedIndexPath = indexPath
        super.init(nibName: nil, bundle: nil)//控制器构造函数一般要用这个
        //不一定能下载daotuoian
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:--- 测试属性有咩有赋值成功
    //    override func viewDidLoad() {
    //        printLog(urls)
    //        printLog(selectedIndexPath)
    //    }
    //MARK:--- 在布局完成时，定位到用户选择的图片
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //定位scrollView
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        //定位分页控件
        pageControl.currentPage = selectedIndexPath.item
    }
    //MARK:--- 设置界面
    override func loadView() {
        //1.创建全屏的视图
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20//间距效果
        view = UIView(frame: rect)
        view.backgroundColor = UIColor.blackColor()
        //2.设置界面
        setupUI()
    }
    func setupUI(){
        //1.添加控件
        view.addSubview(collectionView)
        view.addSubview(saveBtn)
        view.addSubview(closeBtn)
        view.addSubview(pageControl)
        //2.设置布局
        collectionView.frame = view.bounds
        //自动布局
        saveBtn.translatesAutoresizingMaskIntoConstraints = false
        closeBtn.translatesAutoresizingMaskIntoConstraints = false
        pageControl.translatesAutoresizingMaskIntoConstraints = false
        let viewDict = ["saveBtn":saveBtn,"closeBtn":closeBtn]
        //水平上：保存按钮左距离屏8宽80距离关闭按钮至少8，然后关闭按钮宽80距离右屏8
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[saveBtn(80)]-(>=8)-[closeBtn(80)]-28-|", options: [], metrics: nil, views: viewDict))
        //数值上：保存和关闭按钮高35距离屏底部8
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[saveBtn(35)]-8-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn(35)]-8-|", options: [], metrics: nil, views: viewDict))
        //布局分页控件：水平X同View的X；竖直：底部在view的底部靠上8的位置
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: -10))
        view.addConstraint(NSLayoutConstraint(item: pageControl, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -8))
        //3.完善collectionView相关属性和注册cell
        prepareCollectionView()
        preparePageControl()
        //4.用RAC 信号监听关闭按钮
        closeBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
            self?.dismissViewControllerAnimated(true, completion: nil)
        }
        saveBtn.rac_signalForControlEvents(.TouchUpInside).subscribeNext { [weak self](btn) -> Void in
            self?.savaImage()
        }
        //5.监听分页控件的左右点击
        pageControl.rac_signalForControlEvents(.ValueChanged).subscribeNext { (pageControl) -> Void in
            let indexPath = NSIndexPath(forItem: pageControl.currentPage, inSection: 0)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
        }
    }
    //MARK:--- 准备分页控件
    private func preparePageControl()
    {
        pageControl.numberOfPages = urls.count
        pageControl.hidesForSinglePage = true//单页隐藏
        pageControl.pageIndicatorTintColor = UIColor.whiteColor()
        pageControl.currentPageIndicatorTintColor = UIColor.redColor()
    }
    //MARK:--- 准备collectionView
    private func prepareCollectionView(){
        //1.注册可重用cell
        collectionView.registerClass(YAPicBrowserCell.self, forCellWithReuseIdentifier: YAPicBrowserCellID)
        //2.设置数据源
        collectionView.dataSource = self
        collectionView.delegate = self
        //3.设置布局属性
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size//设置每个cell的大小和collectionView一样大
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        //方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        //翻页
        collectionView.pagingEnabled = true
        
    }
    //MARK:--- 懒加载控件
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    ///  保存按钮
    private lazy var saveBtn : UIButton = UIButton(title: "保存", fontSize: 14)
    ///  关闭按钮
    private lazy var closeBtn:UIButton = UIButton(title: "关闭", fontSize: 14)
    //添加分页控件
    private lazy var pageControl:UIPageControl = UIPageControl()
    //MARK:--- 保存照片的缩放比例 swift的extension中不能包含存储型属性
    private var photoScale:CGFloat = 1
}
// MARK:- 实现collectionView的数据源方法及代理方法
extension YAPicBrowserController:UICollectionViewDataSource,UICollectionViewDelegate{
    //MARK:--- cell显示后及时改变分页情况 indexPath:指的上一个cell
    func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        pageControl.currentPage = collectionView.indexPathsForVisibleItems().last?.item ?? 0
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YAPicBrowserCellID, forIndexPath: indexPath) as! YAPicBrowserCell
        // cell.backgroundColor = UIColor.randomColor()
        //指定cell缩放的代理
        cell.photoDelegate = self
        cell.url = urls[indexPath.item]
        return cell
    }
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.LightContent;
    }
}
//实现cell的缩放协议
extension YAPicBrowserController:YAPicBrowserCellDelegate{
    //MARK:--- 缩放完成
    func photoBrowserCellDidZoomed() {
        //小于0.8 一旦调用了dismiss 会触发animator中的解除转场动画的方法
        //从当前的动画状态继续完成后续的转场动画，结束后交给系统的转场
        if photoScale < 0.8 {
            completeTransition(true)
        }
        else{
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1.0
                }){_ in
                    self.hideControllers(false)
                   }
        }
    }
    //MARK:--- 缩放过程中
    func photoBrowserCellDidZooming(scale: CGFloat) {
        // print(scale)
        
        //记录缩放比例 交互动画时 用
        photoScale = scale
        //显示或者隐藏控件
        hideControllers(scale < 1.0)
        if scale < 1.0 {
            //startInd
            startInteractiveTransition(self)//可以让Modal出来的View缩放
        }
        else{//考虑缩放过大的情况
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
    }
    
    //MARK:--- 缩放照片浏览器视图缩放时隐藏
    private func hideControllers(isHidden:Bool){
        closeBtn.hidden = isHidden
        saveBtn.hidden = isHidden
        //分页控件一旦设置了hidden单页隐藏无效
        pageControl.hidden = (urls.count == 1) ? true :isHidden
        
        //修改下背景颜色
        let color = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        view.backgroundColor = color
        collectionView.backgroundColor  = color
    }
}
//实现交互动画的协议
extension YAPicBrowserController:UIViewControllerInteractiveTransitioning
{
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        self.view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        self.view.alpha = photoScale
    }
}
//实现转场动画的上下文协议
extension YAPicBrowserController:UIViewControllerContextTransitioning
{
    // This must be called whenever a transition completes (or is cancelled.)
    // Typically this is called by the object conforming to the
    // UIViewControllerAnimatedTransitioning protocol that was vended by the transitioning
    // delegate.  For purely interactive transitions it should be called by the
    // interaction controller. This method effectively updates internal view
    // controller state at the end of the transition.
    func completeTransition(didComplete: Bool){
        dismissViewControllerAnimated(true, completion: nil)
    }
    // The view in which the animated transition should take place.
    @available(iOS 2.0, *)
    func containerView() -> UIView?{return self.view}
    
    // Most of the time this is YES. For custom transitions that use the new UIModalPresentationCustom
    // presentation type we will invoke the animateTransition: even though the transition should not be
    // animated. This allows the custom transition to add or remove subviews to the container view.
    func isAnimated() -> Bool{return true}
    
    func isInteractive() -> Bool {return true}// This indicates whether the transition is currently interactive.
    
    func transitionWasCancelled() -> Bool {return true}
    
    func presentationStyle() -> UIModalPresentationStyle {return UIModalPresentationStyle.Custom}
    // It only makes sense to call these from an interaction controller that
    // conforms to the UIViewControllerInteractiveTransitioning protocol and was
    // vended to the system by a container view controller's delegate or, in the case
    // of a present or dismiss, the transitioningDelegate.
    func updateInteractiveTransition(percentComplete: CGFloat){}
    func finishInteractiveTransition(){}
    func cancelInteractiveTransition(){}
    
    
    
    // Currently only two keys are defined by the
    // system - UITransitionContextToViewControllerKey, and
    // UITransitionContextFromViewControllerKey.
    // Animators should not directly manipulate a view controller's views and should
    // use viewForKey: to get views instead.
    @available(iOS 2.0, *)
    func viewControllerForKey(key: String) -> UIViewController?{return self}
    
    // Currently only two keys are defined by the system -
    // UITransitionContextFromViewKey, and UITransitionContextToViewKey
    // viewForKey: may return nil which would indicate that the animator should not
    // manipulate the associated view controller's view.
    @available(iOS 8.0, *)
    func viewForKey(key: String) -> UIView?{return self.view}
    
    @available(iOS 8.0, *)
    func targetTransform() -> CGAffineTransform{return CGAffineTransformIdentity}
    
    // The frame's are set to CGRectZero when they are not known or
    // otherwise undefined.  For example the finalFrame of the
    // fromViewController will be CGRectZero if and only if the fromView will be
    // removed from the window at the end of the transition. On the other
    // hand, if the finalFrame is not CGRectZero then it must be respected
    // at the end of the transition.
    @available(iOS 2.0, *)
    func initialFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}
    @available(iOS 2.0, *)
    func finalFrameForViewController(vc: UIViewController) -> CGRect {return CGRectZero}
}